#!/usr/bin/env python3
# scripts/start_services.py

import subprocess
import time
import sys
import os
import platform
from pathlib import Path

def check_redis_installed():
    """检查Redis是否已安装"""
    try:
        # 检查redis-server命令是否可用
        result = subprocess.run(['redis-server', '--version'], 
                              capture_output=True, text=True, timeout=5)
        return result.returncode == 0
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return False

def check_redis_connection():
    """检查Redis连接是否可用"""
    try:
        # 尝试连接远程Redis服务器
        result = subprocess.run(['redis-cli', '-h', '10.3.244.23', '-p', '36379', 'ping'], 
                              capture_output=True, text=True, timeout=5)
        return result.returncode == 0
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return False

def install_redis_instructions():
    """显示Redis安装指导"""
    system = platform.system().lower()
    print("\n📋 Redis安装指导:")
    
    if system == "windows":
        print("Windows用户:")
        print("1. 下载Redis for Windows: https://github.com/microsoftarchive/redis/releases")
        print("2. 或者使用Chocolatey: choco install redis-64")
        print("3. 或者使用WSL2运行Linux版本的Redis")
        print("4. 或者使用Docker: docker run -d -p 6379:6379 redis:alpine")
    elif system == "darwin":  # macOS
        print("macOS用户:")
        print("1. 使用Homebrew: brew install redis")
        print("2. 或者使用Docker: docker run -d -p 6379:6379 redis:alpine")
    else:  # Linux
        print("Linux用户:")
        print("1. Ubuntu/Debian: sudo apt-get install redis-server")
        print("2. CentOS/RHEL: sudo yum install redis")
        print("3. 或者使用Docker: docker run -d -p 6379:6379 redis:alpine")

def start_redis():
    """启动Redis服务"""
    print("正在检查Redis连接...")
    
    # 首先检查远程Redis连接
    if check_redis_connection():
        print("✅ 远程Redis连接正常 (10.3.244.23:36379/6)")
        return True
    
    # 如果远程连接失败，检查本地Redis
    print("⚠️  远程Redis连接失败，检查本地Redis...")
    
    # 检查Redis是否已安装
    if not check_redis_installed():
        print("❌ Redis未安装或不在PATH中")
        install_redis_instructions()
        
        # 询问用户是否继续
        while True:
            choice = input("\n是否跳过Redis启动继续运行其他服务? (y/n): ").lower().strip()
            if choice in ['y', 'yes', '是']:
                print("⚠️  跳过Redis启动，某些功能可能不可用")
                return True
            elif choice in ['n', 'no', '否']:
                print("请先安装Redis后再运行此脚本")
                return False
            else:
                print("请输入 y 或 n")
    
    try:
        # 检查本地Redis是否已运行
        result = subprocess.run(['redis-cli', 'ping'], 
                              capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            print("✅ 本地Redis服务已在运行")
            return True
        
        # 启动本地Redis
        print("正在启动本地Redis服务器...")
        redis_process = subprocess.Popen(
            ['redis-server'], 
            stdout=subprocess.DEVNULL, 
            stderr=subprocess.DEVNULL
        )
        
        # 等待Redis启动
        time.sleep(3)
        
        # 验证Redis是否启动成功
        result = subprocess.run(['redis-cli', 'ping'], 
                              capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            print("✅ 本地Redis服务启动成功")
            return True
        else:
            print("❌ 本地Redis服务启动失败")
            return False
            
    except subprocess.TimeoutExpired:
        print("❌ Redis连接超时")
        return False
    except Exception as e:
        print(f"❌ 启动Redis时发生错误: {e}")
        return False

def start_celery_worker():
    """启动Celery Worker"""
    print("正在启动Celery Worker...")
    try:
        # 启动Celery Worker
        worker_process = subprocess.Popen([
            'celery', '-A', 'tasks.celery_app', 'worker',
            '--loglevel=info',
            '--concurrency=4',  # 并发数
            '--pool=prefork'
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        time.sleep(3)
        
        if worker_process.poll() is None:
            print("✅ Celery Worker启动成功")
            return worker_process
        else:
            print("❌ Celery Worker启动失败")
            return None
    except Exception as e:
        print(f"❌ 启动Celery Worker时发生错误: {e}")
        return None

def start_celery_monitor():
    """启动Celery Monitor"""
    print("正在启动Celery Monitor...")
    try:
        monitor_process = subprocess.Popen([
            'celery', '-A', 'tasks.celery_app', 'flower',
            '--port=5555'
        ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        
        time.sleep(2)
        
        if monitor_process.poll() is None:
            print("✅ Celery Monitor启动成功 (http://localhost:5555)")
            return monitor_process
        else:
            print("❌ Celery Monitor启动失败")
            return None
    except Exception as e:
        print(f"❌ 启动Celery Monitor时发生错误: {e}")
        return None

def start_main_app():
    """启动主应用"""
    print("正在启动主应用...")
    try:
        # 获取multimodal-rag-system目录的路径
        script_dir = os.path.dirname(os.path.abspath(__file__))
        project_dir = os.path.dirname(script_dir)
        
        print(f"脚本目录: {script_dir}")
        print(f"项目目录: {project_dir}")
        
        # 检查项目目录是否存在
        if not os.path.exists(os.path.join(project_dir, 'app')):
            print("❌ 找不到app目录，请确保在正确的项目目录中运行")
            return None
        
        # 在项目目录中启动应用
        app_process = subprocess.Popen([
            'python', 'run.py'
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=project_dir)
        
        time.sleep(3)
        
        if app_process.poll() is None:
            print("✅ 主应用启动成功 (http://localhost:8000)")
            return app_process
        else:
            # 获取错误输出
            stdout, stderr = app_process.communicate()
            print("❌ 主应用启动失败")
            if stderr:
                print(f"错误信息: {stderr.decode('utf-8', errors='ignore')}")
            if stdout:
                print(f"输出信息: {stdout.decode('utf-8', errors='ignore')}")
            return None
    except Exception as e:
        print(f"❌ 启动主应用时发生错误: {e}")
        return None

def main():
    """主函数"""
    print("=== 多模态RAG系统服务启动器 ===")
    
    # 创建必要的目录
    os.makedirs("data/uploads", exist_ok=True)
    os.makedirs("data/uploads/documents", exist_ok=True)
    os.makedirs("data/uploads/images", exist_ok=True)
    os.makedirs("data/uploads/videos", exist_ok=True)
    os.makedirs("data/uploads/temp", exist_ok=True)
    os.makedirs("data/processed", exist_ok=True)
    os.makedirs("data/processed/chunks", exist_ok=True)
    os.makedirs("data/processed/frames", exist_ok=True)
    os.makedirs("data/processed/vectors", exist_ok=True)
    os.makedirs("data/logs", exist_ok=True)
    
    processes = []
    
    try:
        print("⚠️  跳过Redis和Celery服务，直接启动主应用...")
        
        # 启动主应用
        app_process = start_main_app()
        if app_process:
            processes.append(("主应用", app_process))
        else:
            print("❌ 主应用启动失败")
            return
        
        print("\n=== 服务启动完成 ===")
        print("🌐 服务地址:")
        print("- 主应用: http://localhost:8000")
        print("- API文档: http://localhost:8000/docs")
        print("\n⚠️  注意: Redis和Celery服务未启动，异步功能不可用")
        print("按 Ctrl+C 停止服务")
        
        # 等待用户中断
        while True:
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n正在停止所有服务...")
        
        # 停止所有进程
        for name, process in processes:
            print(f"正在停止 {name}...")
            try:
                process.terminate()
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                process.kill()
            except Exception as e:
                print(f"停止 {name} 时发生错误: {e}")
        
        print("✅ 所有服务已停止")

if __name__ == "__main__":
    main() 